document.addEventListener('DOMContentLoaded', () => {

    // --- DOM Elements ---
    const chancesCountSpan = document.getElementById('chances-count');
    const blindBoxContainer = document.getElementById('blind-box');
    const orb = document.querySelector('.orb');
    const carouselContainer = document.getElementById('carousel-container');
    const carouselTrack = document.getElementById('carousel-track');
    const noChancesContainer = document.getElementById('no-chances');
    const modal = document.getElementById('modal');
    const closeModalButton = document.getElementById('close-modal');
    const ignoreButton = document.getElementById('ignore-button');
    const greetButton = document.getElementById('greet-button');
    const confettiCanvas = document.getElementById('confetti-canvas');

    // --- State ---
    let chancesLeft = 3;
    let isSpinning = false;
    let winningItem = null;

    // --- Mock Data ---
    const usersData = [
        { "nickname": "艾米丽", "avatarUrl": "https://images.unsplash.com/photo-1580489944761-15a19d654956?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=100&q=80", "gender": 0, "age": 28, "hometown": "上海", "selfIntroduction": "热爱艺术和旅行，希望找到一个有趣的灵魂伴侣。", "height": 165, "education": "硕士", "occupation": "设计师" },
        { "nickname": "杰克", "avatarUrl": "https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=100&q=80", "gender": 1, "age": 31, "hometown": "北京", "selfIntroduction": "喜欢健身和看电影，性格稳重，有责任心。", "height": 180, "education": "本科", "occupation": "产品经理" },
        { "nickname": "苏菲", "avatarUrl": "https://images.unsplash.com/photo-1494790108377-be9c29b29330?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=100&q=80", "gender": 0, "age": 26, "hometown": "广州", "selfIntroduction": "美食爱好者，喜欢探索城市里的小众餐厅。", "height": 162, "education": "本科", "occupation": "市场专员" },
        { "nickname": "戴维", "avatarUrl": "https://wza-1359813645.cos.ap-beijing.myqcloud.com/images/2025/05/23/107_20250523151049A001.jpg", "gender": 1, "age": 32, "hometown": "河北邢台", "selfIntroduction": "性格开朗，喜欢户外运动，热爱生活。工作稳定，有上进心。", "height": 178, "education": "本科", "occupation": "软件工程师" },
        { "nickname": "莉莉", "avatarUrl": "https://images.unsplash.com/photo-1610276198568-eb6d0ff53e48?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=100&q=80", "gender": 0, "age": 29, "hometown": "杭州", "selfIntroduction": "爱猫人士，喜欢宅家看剧，也喜欢偶尔的city walk。", "height": 168, "education": "本科", "occupation": "运营" },
        { "nickname": "汤姆", "avatarUrl": "https://images.unsplash.com/photo-1564564321837-a57b7070ac4f?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=100&q=80", "gender": 1, "age": 35, "hometown": "深圳", "selfIntroduction": "创业者，工作狂，但懂得享受生活。", "height": 175, "education": "博士", "occupation": "公司创始人" },
        { "nickname": "格蕾丝", "avatarUrl": "https://images.unsplash.com/photo-1544005313-94ddf0286df2?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=100&q=80", "gender": 0, "age": 27, "hometown": "成都", "selfIntroduction": "无辣不欢，喜欢热闹，朋友们都说我是个小太阳。", "height": 166, "education": "本科", "occupation": "教师" },
        { "nickname": "山姆", "avatarUrl": "https://images.unsplash.com/photo-1557862921-37829c790f19?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=100&q=80", "gender": 1, "age": 30, "hometown": "重庆", "selfIntroduction": "摄影师，用镜头记录生活的美好。", "height": 182, "education": "大专", "occupation": "自由职业" }
    ];
    
    // --- Functions ---

    /**
     * 更新视图
     */
    const updateView = () => {
        chancesCountSpan.textContent = chancesLeft;
        
        blindBoxContainer.classList.remove('is-visible');
        carouselContainer.classList.remove('is-visible');
        noChancesContainer.classList.remove('is-visible');

        if (chancesLeft > 0) {
            blindBoxContainer.classList.add('is-visible');
        } else {
            noChancesContainer.classList.add('is-visible');
        }
    };

    /**
     * 更新个人资料卡片内容
     */
    const updateProfileCard = (data) => {
        document.getElementById('avatar').src = data.avatarUrl;
        document.getElementById('nickname').textContent = data.nickname;
        document.getElementById('age-gender').textContent = `${data.age} · ${data.gender === 1 ? '♂' : '♀'}`;
        document.getElementById('self-introduction').textContent = data.selfIntroduction;
        document.getElementById('height').textContent = `身高 ${data.height}cm`;
        document.getElementById('occupation').textContent = data.occupation;
        document.getElementById('education').textContent = data.education;
        document.getElementById('hometown').textContent = data.hometown;
    };

    /**
     * 填充轮播轨道
     */
    const populateCarousel = () => {
        carouselTrack.innerHTML = '';
        const baseItems = usersData;
        const totalItems = 50; 

        let items = [];
        for (let i = 0; i < totalItems; i++) {
            items.push(baseItems[i % baseItems.length]);
        }
        
        for (let i = items.length - 11; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [items[i], items[j]] = [items[j], items[i]];
        }
        
        items.forEach(user => {
            const itemEl = document.createElement('div');
            itemEl.className = 'carousel-item';
            itemEl.innerHTML = `
                <img src="${user.avatarUrl}" alt="${user.nickname}">
                <div class="nickname">${user.nickname}</div>
            `;
            carouselTrack.appendChild(itemEl);
        });
    };

    /**
     * 处理开启动画
     */
    const spinCarousel = () => {
        isSpinning = true;
        blindBoxContainer.classList.remove('is-visible');
        carouselContainer.classList.add('is-visible');
        carouselContainer.classList.add('spinning'); // 开始动画
        
        const items = Array.from(carouselTrack.children);
        const itemWidth = items[0].offsetWidth;
        const itemMargin = parseInt(window.getComputedStyle(items[0]).marginRight) * 2;
        const totalItemWidth = itemWidth + itemMargin;
        
        const trackContainer = carouselTrack.parentElement;
        const windowWidth = trackContainer.offsetWidth;

        carouselTrack.style.transition = 'none';
        carouselTrack.style.transform = 'translateX(0px)';

        setTimeout(() => {
            const winningIndex = Math.floor(Math.random() * (items.length - 10)) + 5;
            winningItem = items[winningIndex];
            
            const winningUser = usersData.find(u => u.nickname === winningItem.querySelector('.nickname').textContent) || usersData[0];
            updateProfileCard(winningUser);

            const offset = (windowWidth / 2) - (totalItemWidth / 2);
            const finalPosition = -(winningIndex * totalItemWidth - offset);
            
            carouselTrack.style.transition = 'transform 6s cubic-bezier(0.2, 0.8, 0.25, 1)';
            carouselTrack.style.transform = `translateX(${finalPosition}px)`;

            carouselTrack.addEventListener('transitionend', () => {
                carouselContainer.classList.remove('spinning'); // 结束动画
                winningItem.classList.add('highlight');
                setTimeout(() => {
                    modal.classList.add('visible');
                    triggerConfetti(); // 触发撒花
                }, 1000); 
            }, { once: true });
        }, 100);
    };

    /**
     * 触发撒花效果
     */
    const triggerConfetti = () => {
        const myConfetti = confetti.create(confettiCanvas, {
            resize: true,
            useWorker: true
        });

        // 减少持续时间和粒子数量
        const duration = 1 * 1000; // 持续时间减半
        const end = Date.now() + duration;

        const colors = ['#00f2ff', '#ff00c1', '#ffffff'];

        (function frame() {
            myConfetti({
                particleCount: 2, // 粒子数量减少
                angle: 60,
                spread: 55,
                origin: { x: 0 },
                colors: colors
            });
            myConfetti({
                particleCount: 2, // 粒子数量减少
                angle: 120,
                spread: 55,
                origin: { x: 1 },
                colors: colors
            });

            if (Date.now() < end) {
                requestAnimationFrame(frame);
        }
        }());
    };

    /**
     * 处理点击能量球
     */
    const handleOrbClick = () => {
        if (chancesLeft <= 0 || isSpinning) return;
        chancesLeft--;
        chancesCountSpan.textContent = chancesLeft;
        spinCarousel();
    };

    /**
     * 关闭弹窗并重置
     */
    const closeModal = () => {
        modal.classList.remove('visible');
        isSpinning = false;
        carouselContainer.classList.remove('spinning'); // 确保移除
        
        if (winningItem) {
            winningItem.classList.remove('highlight');
        }
        
        setTimeout(() => {
            populateCarousel();
            updateView();
        }, 400);
    };

    /**
     * 初始化粒子背景
     */
    const initParticles = () => {
        particlesJS('particles-js', {
            "particles": {
                "number": { "value": 50, "density": { "enable": true, "value_area": 800 } },
                "color": { "value": "#00f2ff" },
                "shape": { "type": "circle" },
                "opacity": { "value": 0.4, "random": true, "anim": { "enable": true, "speed": 0.5, "opacity_min": 0.1, "sync": false } },
                "size": { "value": 2.5, "random": true },
                "line_linked": { "enable": true, "distance": 120, "color": "#00f2ff", "opacity": 0.15, "width": 1 },
                "move": { "enable": true, "speed": 0.8, "direction": "none", "straight": false }
            },
            "interactivity": { "events": { "onhover": { "enable": true, "mode": "repulse" } } },
            "retina_detect": true
        });
    };

    // --- Event Listeners ---
    orb.addEventListener('click', handleOrbClick);
    closeModalButton.addEventListener('click', closeModal);
    ignoreButton.addEventListener('click', closeModal);
    greetButton.addEventListener('click', closeModal);

    // --- Initial Setup ---
    populateCarousel();
    updateView();
    initParticles();
});
